package base;

import java.util.LinkedList;
import java.util.NoSuchElementException;

public class Server
{
	public static int			GLOBAL_ID	= 1;
	public int					id;
	public int					process_power;
	public int					latency;
	public double				date_end;
	public LinkedList<Element>	element_list;
	public LinkedList<Element>	element_list_in;
	public LinkedList<Element>	element_list_out;

	public Server(int process_power, int latency)
	{
		this.id = GLOBAL_ID++;
		this.latency = latency;
		this.process_power = process_power;
		element_list = new LinkedList<Element>();
	}

	public void add(Element el)
	{
		element_list_in.add(el);
	}

	public void run()
	{
		for (Element el_in : element_list_in)
		{
			tryToProceedCompareTo(el_in);
			add(el_in);
		}
	}

	private void tryToProceedCompareTo(Element el_in)
	{
		try
		{
			while (element_list.getFirst().getDateEnd() <= el_in.getDateOut())
			{
				send(element_list.removeFirst());

				Element el = element_list.getFirst();
				date_end += proceed(el_in);
				el.setDateEnd(date_end);
			}
		}
		catch (NoSuchElementException e)
		{
			date_end = el_in.getDateOut() + proceed(el_in);
			el_in.setDateEnd(date_end);
		}

	}

	private void send(Element el)
	{
		element_list_out.add(el);
	}

	public double proceed(Element el)
	{
		return (el.getWeight() / process_power) + latency;
	}

	/**
	 * 
	 * @return the total weight from this Server.
	 */
	public int getWeight()
	{
		int weight = 0;
		for (Element el : element_list)
		{
			weight += el.getWeight();
		}
		return weight;
	}
}
